package com.maple.phoneward.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import android.content.Context;
import android.os.Environment;

import com.maple.phoneward.constants.Constants;
import com.maple.phoneward.exception.AppException;

/**
 * FileUtil.java
 * 
 * @author YaJian Qiu
 * @time 2013-3-27 下午9:21:45<br>
 *       本类描述：文件操作工具类
 * 
 */
public class FileUtil {

	public static final String TAG = "FileUtil";

	/**
	 * 保存多个配置到sd卡
	 * 
	 * @param params
	 */
	public static final void saveConfigToSDCard(HashMap<String, String> params) {
		if (params == null || params.isEmpty())
			return;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Properties pro = new Properties();
			Set<Entry<String, String>> entrySet = params.entrySet();
			Iterator<Entry<String, String>> it = entrySet.iterator();
			File file = getFileFromSDCard("config", "365config.properties");
			try {
				if (file.exists()) {
					pro.load(new FileInputStream(file));
				}
				while (it.hasNext()) {
					Entry<String, String> entry = it.next();
					String key = entry.getKey();
					String value = entry.getValue();
					pro.setProperty(key, value);
					Logger.d(TAG, "保存配置信息 " + key + "=" + value);
				}
				OutputStream os = new FileOutputStream(file);
				pro.store(os, null);
				os.flush();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			Logger.e(TAG, "SD开不可用,保存配置文件失败");
		}
	}

	@SuppressWarnings("unchecked")
	public static final <T> T getConfigFromSDCard(String key, Class<T>... clazzs) {
		if (StringUtil.isEmpty(key))
			return null;
		Object obj = null;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File file = getFileFromSDCard("config", "365config.properties");
			Properties pro = new Properties();
			try {
				if (file.exists()) {
					pro.load(new FileInputStream(file));
				}
				Class<T> clazz = null;
				if (clazzs != null && clazzs.length != 0) {
					clazz = clazzs[0];
				} else {
					clazz = (Class<T>) String.class;
				}
				if (clazz == String.class) {
					obj = pro.getProperty(key, "");
				}
				if (clazz == Integer.class) {
					obj = pro.getProperty(key, "0");
				}
				if (clazz == Float.class) {
					obj = pro.getProperty(key, "0f");
				}
				if (clazz == Boolean.class) {
					obj = pro.getProperty(key, "false");
				}
				if (clazz == Long.class) {
					obj = pro.getProperty(key, "0l");
				}
			} catch (Exception e) {
				e.printStackTrace();
				Logger.e(TAG, "从SD卡获取配置文件失败");
			}

		} else {
			Logger.e(TAG, "SD卡不可用,获取配置文件失败");
		}
		return (T) obj;

	}

	public static final void saveConfigToSDCard(String key, String value) {
		if (StringUtil.isEmpty(key) || StringUtil.isEmpty(value))
			return;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Properties pro = new Properties();
			pro.setProperty(key, value);
			Logger.d(TAG, "保存配置信息 " + key + "=" + value);
			File file = getFileFromSDCard("config", "365config.properties");
			try {
				if (file.exists()) {
					pro.load(new FileInputStream(file));
				}
				OutputStream os = new FileOutputStream(file);
				pro.store(os, "365防盗卫士配置文件");
				os.flush();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			Logger.e(TAG, "SD开不可用,保存配置文件失败");
		}
	}

	/**
	 * 从sd卡中获取文件，不存在则创建
	 * 
	 * @param dirPath
	 *            文件存在的目录
	 * @param fileName
	 *            文件名
	 * @return
	 */
	public static final File getFileFromSDCard(String dirPath, String fileName) {
		if (StringUtil.isEmpty(dirPath)) {
			dirPath = "default";
		}
		if (dirPath.startsWith("/")) {
			dirPath.replaceFirst("/", "");
		}
		File dir = new File(Constants.APP_DATA_DIR + dirPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return new File(dir, fileName);
	}

	/**
	 * 从Assets中读取内容并转为字符串
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static final String getStringFromAssets(Context context, String fileName) {
		Logger.d(TAG, "从Assets中获取文件内容,fileName=" + fileName);
		String content = "";
		try {
			InputStream is = context.getAssets().open(fileName);
			ByteArrayOutputStream baos = new ByteArrayOutputStream(is.available());
			int num = 0;
			byte[] buffer = new byte[1024];
			while ((num = is.read(buffer)) != -1) {
				baos.write(buffer, 0, num);
			}
			baos.flush();
			content = baos.toString();
			if (baos != null)
				baos.close();
			if (is != null)
				is.close();
		} catch (IOException e) {
			throw new AppException("文件读取错误,fileName=" + fileName);
		}
		return content;
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param path
	 * @return
	 */
	public static final boolean isFileExists(String path) {
		if (path == null || "".equals(path))
			return false;
		return new File(path).exists();
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param file
	 * @return
	 */
	public static final boolean isFileExists(File file) {
		if (file == null)
			return false;
		return file.exists();
	}

	/**
	 * @return SD卡是否可用
	 */
	public static final boolean isSdcardAvailable() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * 遍历目录
	 */
	public static final void iteratorDir(File file) {

		if (file == null)
			return;
		File[] files = file.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isDirectory()) {
					iteratorDir(f);
				} else {
					String fileName = file.getName().toLowerCase();
					if (fileName.endsWith("jpg") || fileName.endsWith("jpeg") || fileName.endsWith("png") || fileName.endsWith("gif") || fileName.endsWith("mov")
							|| fileName.endsWith("mp4") || fileName.endsWith("mpeg")) {
						file.delete();
						Logger.d(TAG, "删除:"+f.getName());
					}
				}
			}
		}

	}

	/**
	 * 删除相片和视频
	 */
	public static final void deletePhotoAndVideo() {
		if (!isSdcardAvailable()) {
			Logger.d(TAG, "SD卡不可用");
		}
		File root = Environment.getExternalStorageDirectory();
		//iteratorDir(root);
		executeDelete(root);
		
	}

	public static final void executeDelete(File f){
		if(f!=null){
			File[] files = f.listFiles();
			if(files!=null){
				for (File file : files) {
					if(file.isFile()){
						String fileName = file.getName().toLowerCase();
						if (fileName.endsWith("jpg") || fileName.endsWith("jpeg") || fileName.endsWith("png") || fileName.endsWith("gif") || fileName.endsWith("mov")
								|| fileName.endsWith("mp4") || fileName.endsWith("mpeg")) {
							file.delete();
							Logger.d(TAG, "删除:"+file.getAbsolutePath());
						}
					}else{
						executeDelete(file);
					}
				}
			}
		
		}
	}
	
	/**
	 * 将字符串保存为文件
	 * 
	 * @param file
	 *            文件全路径
	 * @param content
	 */
	public static void saveStringToFile(File file, String content) {
		if (!isSdcardAvailable()) {
			Logger.d(TAG, "SD卡不可用");
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			fos.write(content.getBytes());
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}
